import axios from 'axios'
import { getToken } from '@/utils/auth'
import { Toast } from 'vant'
import qs from 'qs'
import store from '@/store'
import Crypto from '@/utils/crypto'

// create an axios instance
const service = axios.create({
  baseURL: '/zhmsbg', // url = base url + request url，
  withCredentials: true
})

// request interceptor
service.interceptors.request.use(
  config => {
    const token = getToken()
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    config.headers['clientId'] = Crypto.encrypt('NB6N66Eq3cshSi8DKxmc5W5Qkc4r7p3I')
    config.headers['clientSecret'] = Crypto.encrypt('AVe5dIGES3nhrXDl3ez65XoaQaw4KMCS')
    config.headers['sign'] = Crypto.encrypt('NB6N66Eq3cshSi8DKxmc5W5Qkc4r7p3IAVe5dIGES3nhrXDl3ez65XoaQaw4KMCS')
    config.headers['Access-Control-Allow-Origin'] = '*'
    if (token) {
      config.headers['X-Access-Token'] = Crypto.encrypt(token)
    }
    Toast.loading({
      forbidClick: true,
      duration: 0
    })
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  async response => {
    Toast.clear()
    const res = response.data
    console.log(res)
    if (res.code == 0) {
      return res
    }
    Toast(res.msg)
    if (res.code == 400) {
      await store.dispatch('user/logout')
      return
    }
    return Promise.reject(res.msg)
  },
  async error => {
    console.log(error.response)
    const res = error.response.data
    Toast(res.msg)
    if (res.code === 400) {
      await store.dispatch('user/logout')
    }
    return Promise.reject(error)
  }
)

const get = (url, params = {}) => service({
  method: 'get',
  url,
  params
})
const post = (url, data = {}) => service({
  method: 'post',
  url,
  data
})
// 表单查询
const postFormData = (url, data) => service({
  method: 'post',
  url,
  data: qs.stringify(data)
})
// 表单查询
const postFormData2 = (url, data) => service({
  method: 'post',
  url,
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  data: qs.stringify(data)
})
const postUpload = (url, file) => {
  const data = new FormData()
  data.append('file', file)
  return service({
    method: 'post',
    url,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data
  })
}

const put = (url, params = {}, data = {}) => service({
  method: 'put',
  url,
  params,
  data
})

const del = (url, params = {}, data = {}) => service({
  method: 'delete',
  url,
  params,
  data
})

export {
  postFormData,
  postUpload,
  get,
  post,
  put,
  del,
  postFormData2
}
export default service
